package nio;


import sun.nio.ch.IOUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * User: Administrator
 * Date: 2021/3/30
 * Time: 17:01
 * Description:
 */
public class FileNioCopy {
    public static void main(String[] args) throws IOException {
        File srcFile = new File("C:\\Users\\Administrator\\Desktop\\copy.txt");
        File destFile = new File("C:\\Users\\Administrator\\Desktop\\copy2.txt");
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        long start = System.currentTimeMillis();
        FileInputStream in = null;
        FileOutputStream out = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;

        in = new FileInputStream(srcFile);
        out = new FileOutputStream(destFile);
        inChannel = in.getChannel();
        outChannel = out.getChannel();
        int length = -1;
        ByteBuffer buf = ByteBuffer.allocate(1024);

        while((length = inChannel.read(buf)) != -1){
            buf.flip();

            int outlength = 0;

            while ((outlength = outChannel.write(buf)) != 0) {
                System.out.println("写入" + outlength);
            }

            buf.clear();
        }

        outChannel.force(true);

        in.close();
        out.close();
        inChannel.close();
        outChannel.close();

        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
